#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author:heqiang

"""
app id :wx06c79109521e34d2

"""

# 扫码登录微信
# from wxpy import *
# bot = Bot(cache_path=True)
#
# bot.file_helper.send("hello")
import time

import requests
from urllib import parse
from flask import Flask, request, make_response
import json
import datetime
import messageManage
import model

appkey = "173aee16726d444bb1f61025dd9cef74"
sid = "36576"
pid = "mm_55844929_1958550315_110731150452"



def tkl_api(tkl):
    url = "https://api.zhetaoke.com:10001/api/open_gaoyongzhuanlian_tkl.ashx"
    tkl_urlencode = parse.quote(tkl)
    formData = "appkey=%s&sid=%s&pid=%s&tkl=%s&signurl=5" % (appkey, sid, pid, tkl_urlencode)
    # print(formData)
    con = requests.get(url=url + "?" + formData)
    res = con.text
    print(res)
    if con.status_code == 200 and "\"status\":200" in res:

        product_messages = json.loads(res)["content"][0]
        # print(dd["content"])
        info_tuple = (product_messages["title"], product_messages["tkl"], product_messages["size"],
                      product_messages["coupon_info_money"], product_messages["quanhou_jiage"],
                      product_messages["tkfee3"], product_messages["tkfee3"])
        info = messageManage.FANLIINFO % info_tuple
        re_time = product_messages["date_time_yongjin"].replace("/","-")
        model.add_tkl_record("user234", "32", re_time, product_messages["tkl"],
                             product_messages["tao_id"], product_messages["tkfee3"])
        return True, info, product_messages["tao_id"]
    else:
        return False, "返回错误，请检查参数", None


def get_order_url_day(starttime, query_type="1", tk_status="3", order_scene="1", signurl=1):
    """
    starttime : string  2022-01-01
    # 查询某一天的订单
    返回的是url list。以20分钟为间隔
    """

    url = "https://api.zhetaoke.com:10001/api/open_dingdanchaxun2_piliang.ashx"
    # endtime = datetime.datetime.strptime(starttime, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(hours=3)
    formData = "appkey=%s&sid=%s&start_time=%s&query_type=%s&tk_status=%s&order_scene=%s&signurl=%d" % (
        appkey, sid, starttime, query_type, tk_status, order_scene, signurl)
    # print(formData)
    con = requests.get(url=url + "?" + formData)
    if con.status_code == 200:
        res = con.text
        messages = json.loads(res)
        for orderurl in messages:
            parser_tb_url(orderurl["url"])
    else:
        raise Exception(con.text)

def check_order_tkl(trade_id,tao_id,tb_paid_time):
        """
        先检查前10分钟内有无，对应口令，再30，再60
        对查找到的tkl count+1, order flag 设为f, 对应用户+yongjin
        """
        tklinfos =  model.get_tkl_record(tao_id,tb_paid_time)
        if tklinfos :
            print("start update")
            print(tklinfos)
            #update tkl
            model.update_tkl_count(tklinfos[0],tklinfos[5]+1)
            model.update_oder_flag(trade_id)
            model.add_user_fanli(tklinfos[2],tklinfos[3])

def parser_tb_url(url):
    """
    解析连接中的order，存入表中
    """
    tb_con = requests.get(url=url)
    tb_res = json.loads(tb_con.text)
    if "publisher_order_dto" not in tb_res["tbk_sc_order_details_get_response"]["data"]["results"].keys():
        return None
    else:
        tb_message_list = tb_res["tbk_sc_order_details_get_response"]["data"]["results"][
            "publisher_order_dto"]
        for order in tb_message_list:

            model.add_order(order["item_id"], order["trade_id"], order["tk_commission_fee_for_media_platform"],
                            order["tb_paid_time"])
            check_order_tkl(order["trade_id"],order["item_id"], order["tb_paid_time"])
        return True


def missionTimer():
    while True:
        timedate = datetime.datetime.now()
        timedate = timedate.strftime("%Y-%m-%d")
        get_order_url_day(starttime=str(timedate))
        time.sleep(86400)


if __name__ == "__main__":
    # kouling = tkl_api(
    #     "【淘宝】https://m.tb.cn/h.flO5Z89?tk=JAkP2eXzphb「理然洗面奶男士专用氨基酸洁面乳控油补水保湿洗去黑头护肤品套装」点击链接直接打开")
    # print(kouling)

    # m = get_order_url_day(starttime="2021-08-21")
    # missionTimer()

    check_order_tkl(tao_id="608054988202",trade_id="341324312",tb_paid_time="2022-02-22 16:44:46")
